﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;

/// <summary>去除重复的文字，用于减小 TextMesh Pro 生成文件的大小。</summary>
public class DuplicateTextFilter
{
    static string inputFileName = "Font/Text.txt";

    [MenuItem("Tools/去除重复文字", false, 0)]
    static void DuplicateText() => ProcessText();

    private static void ProcessText()
    {
        // 获取输入文件的完整路径
        string filePath = Path.Combine(Application.dataPath, inputFileName);

        if (!File.Exists(filePath))
        {
            Debug.LogError($"文件不存在：{filePath}");
            return;
        }

        // 读取整个文件内容
        string fileContent = File.ReadAllText(filePath, System.Text.Encoding.UTF8);

        // 逐字检查并除去重复字符串
        string processedContent = RemoveDuplicates(fileContent);

        // 将处理后的内容保存到输出文件中
        File.WriteAllText(filePath, processedContent);

        Debug.Log($"成功去除重复的文字：[{filePath}]");
    }

    private static string RemoveDuplicates(string inputText)
    {
        if (string.IsNullOrEmpty(inputText))
            return string.Empty;

        StringBuilder result = new StringBuilder();
        HashSet<char> seenCharacters = new HashSet<char>();
        inputText += GetCommonCharacter();

        foreach (char currentChar in inputText)
        {
            if (!seenCharacters.Contains(currentChar))
            {
                result.Append(currentChar);
                seenCharacters.Add(currentChar);
            }
        }

        return result.ToString();
    }

    private static string GetCommonCharacter()
    {
        StringBuilder result = new StringBuilder();

        // 获取基本符号
        for (int code = 33; code <= 126; code++)
        {
            char character = (char)code;
            result.Append(character);
        }

        return result.ToString();
    }
}